<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
//@ts-ignore
import Cookies from 'js-cookie'
import request from '@/utils/axios'

const router = useRouter()
const formRef = ref<FormInstance>()

const form = ref({
  username: '',
  password: ''
})

const rules = ref<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

const loading = ref(false)

const handleLogin = async () => {
  if (!formRef.value) return

  try {
    let result = await formRef.value.validate()
    if (!result) return
    loading.value = true

    const { data } = await request.post('/auth/login', form.value)

    // 根据userType设置用户角色
    const roleMap = {
      0: 'admin',
      1: 'counselor',
      2: 'user'
    }
    const userRole = roleMap[data.userType as keyof typeof roleMap] || 'user'
    // 存储认证令牌和用户角色
    Cookies.set('api-token', data.token, { expires: 1 }) // 假设token在data.token中
    Cookies.set('user-role', userRole)
    ElMessage.success('登录成功')
    console.log(data)
    // 根据用户角色跳转到对应的首页
    if (userRole === 'admin') {
      router.push('/admin/dashboard')
    } else if (userRole === 'counselor') {
      router.push('/admin/counselor-profile')
    } else {
      router.push('/admin/appointments')
    }
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '登录失败，请稍后重试')
    console.error('登录失败：', error)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h2>大学生心理咨询系统</h2>
      <el-form ref="formRef"
        :model="form"
        :rules="rules"
        @submit.prevent="handleLogin">
        <el-form-item prop="username">
          <el-input v-model="form.username"
            class="h-[40px]"
            prefix-icon="el-icon-user"
            placeholder="请输入账号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password"
            type="password"
            class="h-[40px]"
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
            @keyup.enter="handleLogin" />
        </el-form-item>
        <div class="options">
          <a href="#">忘记密码？</a>
        </div>
        <div class="buttons">
          <el-button type="default"
            class="register-btn h-[40px]"
            @click="$router.push('/register')">注册</el-button>
          <el-button type="primary"
            :loading="loading"
            class="login-btn h-[40px]"
            @click="handleLogin">{{ loading ?
              '登录中...' : '登录' }}</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background-color: #e6f7ff;
  position: fixed;
  top: 0;
  left: 0;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.options {
  text-align: right;
  margin: 15px 0;
}

.options a {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.options a:hover {
  color: #66b1ff;
}

.buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.register-btn,
.login-btn {
  width: 48%;
}

.register-btn {
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.register-btn:hover {
  background-color: #e9ecef;
  color: #409eff;
}

.login-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.login-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>
